<?php

namespace Frieza\Modules\TodayPrettyThing\Controllers;

use App\Exceptions\InputErrorException;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\TodayPrettyThing\TodayPrettyThing;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Doraemon\service\TodayPrettyThing\TodayPrettyThing as sTodayPrettyThing;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\cache\TodayPrettyThing as cTodayPrettyThing;

/**
 * @deprecated
 */
class TodayPrettyThingController
{
    const START_YEAR = 2022;

    public function index(Content $content, $year = null, $month = null)
    {
        $year = $year ?? date('Y');
        $month = $month ?? date('m');
        $yearTab = new Tab();
        $monthTab = new Tab();
        for ($i = 1; $i <= 12; $i++) {
            if ($i == $month) {
                $month = str_pad($month, 2, 0, STR_PAD_LEFT);
                $monthTab->add($i . '月', $this->getTodayPrettyThingInfos($year . '-' . $month), true);
            } else {
                $monthTab->addLink($i . '月', "/admin/TodayPrettyThing/index/$year/$i");
            }
        }
        $yearList = range(self::START_YEAR, date('Y') + 1);
        foreach ($yearList as $item) {
            if ($item == $year) {
                $yearTab->add($item, $monthTab, true);
            } else {
                $yearTab->addLink($item, "/admin/TodayPrettyThing/index/$item");
            }
        }
        $yearTab->addLink('话题池', '/admin/TodayPrettyThing/topic');
        $content->row($yearTab);
        return $content
            ->header('今日小事')
            ->description('');
    }

    public function edit(Content $content, $date, $id = null)
    {
        if (!isset($id)) {
            $data['today'] = $date;
        } else {
            $data = TodayPrettyThing::getByParams(['id' => $id], ['id', 'today', 'uid', 'note_id','content', 'pic_id', 'topic_id', 'topic_notes_id']);
        }
        $data['holiday'] = sTodayPrettyThing::getToday(strtotime($date));
        $data['h5'] = 'https://m.haohaozhu.cn/growth/activity/today-small-things/look?date=' . $date;
        if (empty($data['topic_id'])) {
            $data['topic_id'] = 1537; //默认topic_id
        }
        $form = new Form($data);
        $form->hidden('id');
        $form->hidden('today');
        $form->display('today', '日期');
        $form->display('holiday', '节日');
        $form->textarea('content', '今日小事文案');
        $form->imgUpload('pic_id', '日历背景图', false);
        $form->text('topic_id', '专属话题id')->placeholder('默认预置记录我的今日小事话题id');
        $form->text('topic_notes_id', '专属话题外露note')->placeholder('输入noteId, 多条,隔开，最多五条');
        $form->text('note_id', '配图跳转noteId');
        $form->action('/admin/TodayPrettyThing/save');
        $form->disableReset();
        $tab = new Tab();
        $tab->add('今日小事', $form->render(), true);
        return $content
            ->header('日历编辑')
            ->breadcrumb(['text' => '今日小事', 'url' => 'TodayPrettyThing/index'], ['text' => '日历编辑'])
            ->row($tab);
    }

    public static function topic(Content $content)
    {
        $data = [];
        $topTopic = cTodayPrettyThing::getPool(cTodayPrettyThing::TOPIC_TOP_POOL_KEY);
        $topic = cTodayPrettyThing::getPool(cTodayPrettyThing::TOPIC_POOL_KEY);
        if ($topic) {
            $data['pool'] = implode(',', $topic);
        }
        if ($topTopic) {
            $data['top'] = implode(',', $topTopic);
        }
        $form = new Form($data);
        $form->textarea('pool', '话题池')->help('多个话题使用英文","隔开，顺延即可，不要回车');
        $form->textarea('top', '人工置顶')->help('多个英文,隔开');
        $form->action('/admin/TodayPrettyThing/topic/save');
        $tab = new Tab();
        $tab->add('话题池', $form->render());
        return $content->header('话题池编辑')->breadcrumb(['text' => '今日小事', 'url' => 'TodayPrettyThing/index'], ['text' => '话题池编辑'])->row($tab);
    }

    public static function topicSave(Request $request)
    {
        $all = $request->all();
        $topPool = [];
        $topicPool = [];
        if ($all['pool']) {
            $topicPool = explode(',', $all['pool']);
            foreach ($topicPool as $id) {
                if (!is_numeric($id)) {
                    throw new InputErrorException('id非法,请重试', InputErrorException::DEFAULT_CODE, 'pool');
                }
            }
        }
        if ($all['top']) {
            $topPool = explode(',', $all['top']);
            foreach ($topPool as $id) {
                if (!is_numeric($id)) {
                    throw new InputErrorException('id非法,请重试', InputErrorException::DEFAULT_CODE, 'top');
                }
            }
        }
        $setInTopPool = cTodayPrettyThing::setInTopicPool($topPool, cTodayPrettyThing::TOPIC_TOP_POOL_KEY);
        $setInTopicPool = cTodayPrettyThing::setInTopicPool($topicPool, cTodayPrettyThing::TOPIC_POOL_KEY);
        if ($setInTopicPool || $setInTopPool) {
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/TodayPrettyThing/topic')->with(compact('success'));
        }
        $error = new MessageBag([
            'title' => '保存失败，请重试'
        ]);
        return redirect('/admin/TodayPrettyThing/topic')->with(compact('error'));
    }

    public static function save(Request $request)
    {
        $all = $request->all();
        if (!$all['pic_id']) {
            throw new InputErrorException('请设置背景图', InputErrorException::DEFAULT_CODE, 'pic_id');
        }
        if (!$all['note_id']) {
            throw new InputErrorException('请设置NoteId', InputErrorException::DEFAULT_CODE, 'note_id');
        }
        if (!$all['content']) {
            throw new InputErrorException('请设置正文', InputErrorException::DEFAULT_CODE, 'content');
        }

        $all['discuss'] = TodayPrettyThing::TYPE_NULL;
        $all['discuss_id'] = TodayPrettyThing::TYPE_NULL;
        $all['topic_notes_id'] = trim($all['topic_notes_id'], ',');

        if (strpos($all['topic_notes_id'], '，')) {
            throw new InputErrorException(',应为英文逗号', InputErrorException::DEFAULT_CODE, 'topic_notes_id');
        }

        unset($all['base'], $all['link_params'], $all['_token']);

        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        if ($all['id'] >= 0 && $all['id']) {
            $all['edit_time'] = time();
            if (TodayPrettyThing::updateData($all, ['id' => $all['id']])) {
                return redirect('/admin/TodayPrettyThing/edit/' . $all['today'] . '/' . $all['id'])->with(compact('success'));
            }
        } else {
            $all['thing_status'] = TodayPrettyThing::STATUS_NORMAL;
            $all['addtime'] = time();
            $insertId = TodayPrettyThing::insertData($all);
            if ($insertId) {
                return redirect('/admin/TodayPrettyThing/edit/' . $all['today'] . '/' . $insertId)->with(compact('success'));
            }
        }
        $error = new MessageBag([
            'title' => '保存失败，请重试'
        ]);
        return redirect('/admin/TodayPrettyThing/edit/' . $all['today'] . '/' . $all['id'])->with(compact('error'));
    }

    private function getTodayPrettyLink($date)
    {
        return json_encode(
            [
                'type' => 'link',
                'link' => Hhzurl::getTodayPrettyThing($date)
            ]
        );
    }

    private function getTodayPrettyThingInfos($time)
    {
        $where = [
            'today[~]' => $time,
            'thing_status' => TodayPrettyThing::STATUS_NORMAL
        ];
        $todayPrettyThingInfos = TodayPrettyThing::selectByParams($where, ['today' => ['id', 'today', 'content', 'pic_id']]);
        $maxDay = date('t', strtotime($time));
        $allDayInMonthList = [];
        for ($i = 1; $i <= $maxDay; $i++) {
            $date = date('Y-m-d', strtotime($time . '-' . $i));
            if (isset($todayPrettyThingInfos[$date])) {
                $allDayInMonthList[] = [
                    'id' => $todayPrettyThingInfos[$date]['id'],
                    'link' => $this->getTodayPrettyLink($todayPrettyThingInfos[$date]['today']),
                    'today' => $todayPrettyThingInfos[$date]['today'],
                    'content' => $todayPrettyThingInfos[$date]['content'],
                    'pic' => ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $todayPrettyThingInfos[$date]['pic_id'], ImgUrl::IMAGE_SIZE_OP_ORI),
                    'holiday' => sTodayPrettyThing::getToday(strtotime($todayPrettyThingInfos[$date]['today'])),
                ];
            } else {
                $allDayInMonthList[] = [
                    'today' => $date,
                    'holiday' => sTodayPrettyThing::getToday(strtotime($date))
                ];
            }
        }
        $gridModel = new pGridDataModel($allDayInMonthList, $maxDay, [
            'keyName' => 'today'
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disablePagination();

            $grid->column('link', '预览二维码')->newQrcode();
            $grid->column('today', '日期');
            $grid->column('holiday', '节日');
            $grid->column('content', '今日小事文案');
            $grid->column('pic', '日历背景图')->image();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();

                if (isset($actions->row->id)) {
                    $actions->append('<a href="/admin/TodayPrettyThing/edit/' . $actions->row->today . '/' . $actions->row->id . '" class="fa fa-edit">编辑</a>');
                } else {
                    $actions->append('<a href="/admin/TodayPrettyThing/edit/' . $actions->row->today . '" class="fa fa-edit">新增</a>');
                }
            });
        });
        return $listGrid->render();
    }

}